<template>
  <a-spin :spinning="confirmLoading">
    <j-form-container :disabled="formDisabled">
      <!-- 主表单区域 -->
      <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
        <a-row>
          <a-col :span="8">
            <a-form-model-item label="包装入库单号" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="entryNumber">
              <a-input v-model="model.entryNumber" placeholder="保存自动生成" disabled></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="包装车间" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="packagingWorkshopCode">
              <j-search-select-tag
                    type="list"
                    v-model="model.packagingWorkshopCode"
                    :dictOptions="dictOptions"
                    placeholder="请选择包装车间"
                    @change="handlePackshopChange"
                  />
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="包装班组" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="packagingTeamId">
              <a-select v-model="model.packagingTeamId" placeholder="请选择包装班组" @change="handleTeamChangeAndValidate">
                <a-select-option v-for="item in teamlist" :key="item.id" :value="item.id">
                  {{ item.team }}
                </a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item
              label="备注"
              :labelCol="{ xs: { span: 24 }, sm: { span: 1 } }"
              :wrapperCol="{ xs: { span: 24 }, sm: { span: 22 } }"
              prop="remark"
            >
              <a-input v-model="model.remark" placeholder="请输入备注"></a-input>
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>
    </j-form-container>
    <!-- 子表单区域 -->
    <a-tabs v-model="activeKey" @change="handleChangeTabs">
      <a-tab-pane tab="包装日报" :key="refKeys[0]" :forceRender="true">
        <a-row :gutter="10">
          <a-col :md="16" :sm="24">
            <a-row :gutter="20" style="margin-bottom: 5px; margin-top: 7px">
              <a-col :span="2">
                <a-button @click="changeMaterial" :disabled="formDisabled">变更物料</a-button>
              </a-col>
            </a-row>
            <a-row>
              <!-- 包装日报 -->
              <j-vxe-table
                v-if="ifFenerateColumns"
                keep-source
                :ref="refKeys[0]"
                :loading="packagingInboundOrderGroupTable.loading"
                @click.native="handleRowClick"
                :columns="packagingInboundOrderGroupTable.columns"
                :dataSource="packagingInboundOrderGroupTable.dataSource"
                :maxHeight="450"
                :disabled="formDisabled"
                :rowNumber="true"
                :rowSelection="false"
                :clickSelectRow="false"
                class="j-table-force-nowrap1"
                type="complex"
              >
                <template #parentHeader>
                </template>
                <template v-for="item in materialColumns" :slot="`${item.materialName}_+_${item.materialCode}`" slot-scope="{row, rowIndex }">
                  <a-input-number :min="0"
                    v-model="row[item.materialName + '_+_' + item.materialCode]" 
                    @change="handleChildInput(row, rowIndex, item.materialName + '_+_' + item.materialCode, item.materialCode)"
                    style="width: 100%; border: none; background: transparent"
                    :disabled="formDisabled || row.groupName === '合计'"
                  />
                </template>
                <template #remark_column="{row}">
                  <a-input 
                    v-model="row.remark" 
                    :disabled="formDisabled || row.groupName === '合计'"
                    style="width: 100%; border: none; background: transparent"
                  />
                </template>
              </j-vxe-table>
            </a-row>
            <a-row>
              <!-- 作业定额 -->
              <j-vxe-table
                v-if="ifFenerateColumns"
                keep-source
                :loading="packagingInboundOrderQuotaTable.loading"
                :columns="packagingInboundOrderQuotaTable.columns"
                :dataSource="packagingInboundOrderQuotaTable.dataSource"
                :maxHeight="330"
                :disabled="formDisabled"
                :rowSelection="false"
                style=" margin-right: 270px"
              >
                <template #parentHeaderQuota>
                </template>
                <template v-for="item in materialColumns" :slot="`${item.materialName}_+_${item.materialCode}`" slot-scope="{row, rowIndex }">
                  <a-input-number :min="0"
                    v-model="row[item.materialName + '_+_' + item.materialCode]" 
                    @change="handleQuotaInput(rowIndex)"
                    style="width: 100%; border: none; background: transparent"
                    :disabled="formDisabled"
                  />
                </template>
              </j-vxe-table>
            </a-row>
          </a-col>
          <a-col :md="8" :sm="24">
            <!-- 小组成员 -->
            <a-row :gutter="20" style="margin-bottom: 5px; margin-top: 7px">
              <a-col :span="2">
                <a-button @click="addMember" :disabled="formDisabled || selectedGroupId=='合计'">新增</a-button>
              </a-col>
            </a-row>
            <j-vxe-table
              keep-source
              :ref="refKeys[4]"
              :loading="packagingInboundOrderMemberTable.loading"
              :columns="packagingInboundOrderMemberTable.columns"
              :dataSource="selectedMembers"
              :maxHeight="612"
              :disabled="formDisabled"
              :rowNumber="true"
              :rowSelection="false"
            >
              <template v-slot:action="{ row }">
                <a-popconfirm 
                  title="确认删除?" 
                  @confirm="() => handleMemberRemove(row)"
                  :disabled="formDisabled"
                >
                  <a :disabled="formDisabled">
                    删除
                  </a>
                </a-popconfirm>
              </template>
            </j-vxe-table>
          </a-col>
        </a-row>
      </a-tab-pane>
      <a-tab-pane tab="小包装日报" :key="refKeys[1]" :forceRender="true">
        <a-row :gutter="10">
          <a-col :md="16" :sm="24">
            <a-row :gutter="20" style="margin-bottom: 5px; margin-top: 7px">
              <a-col :span="2">
                <a-button @click="changeMaterial" :disabled="formDisabled">变更物料</a-button>
              </a-col>
            </a-row>
            <a-row>
              <!-- 小包装日报 -->
              <j-vxe-table
                v-if="ifFenerateColumns"
                keep-source
                :ref="refKeys[1]"
                :loading="packagingInboundOrderGroupSmallTable.loading"
                @click.native="handleSmallRowClick"
                :columns="packagingInboundOrderGroupSmallTable.columns"
                :dataSource="packagingInboundOrderGroupSmallTable.dataSource"
                :maxHeight="450"
                :disabled="formDisabled"
                :rowNumber="true"
                :rowSelection="false"
                :clickSelectRow="false"
                class="j-table-force-nowrap1"
                type="complex"
              >
                <template #parentHeader>
                </template>
                <template v-for="item in materialColumns" :slot="`${item.materialName}_+_${item.materialCode}`" slot-scope="{row, rowIndex }">
                  <a-input-number :min="0"
                    v-model="row[item.materialName + '_+_' + item.materialCode]" 
                    @change="handleChildInput(row, rowIndex, item.materialName + '_+_' + item.materialCode, item.materialCode)"
                    style="width: 100%; border: none; background: transparent"
                    :disabled="formDisabled || row.groupName === '合计'"
                  />
                </template>
                <template #remark_column="{row}">
                  <a-input 
                    v-model="row.remark" 
                    :disabled="formDisabled || row.groupName === '合计'"
                    style="width: 100%; border: none; background: transparent"
                  />
                </template>
              </j-vxe-table>
            </a-row>
            <a-row>
              <!-- 作业定额 -->
              <j-vxe-table
                v-if="ifFenerateColumns"
                keep-source
                :loading="packagingInboundOrderQuotaSmallTable.loading"
                :columns="packagingInboundOrderQuotaSmallTable.columns"
                :dataSource="packagingInboundOrderQuotaSmallTable.dataSource"
                :maxHeight="330"
                :disabled="formDisabled"
                :rowSelection="false"
                style=" margin-right: 270px"
              >
                <template #parentHeaderQuota>
                </template>
                <template v-for="item in materialColumns" :slot="`${item.materialName}_+_${item.materialCode}`" slot-scope="{row, rowIndex }">
                  <a-input-number :min="0"
                    v-model="row[item.materialName + '_+_' + item.materialCode]" 
                    @change="handleQuotaInput(rowIndex)"
                    style="width: 100%; border: none; background: transparent"
                    :disabled="formDisabled"
                  />
                </template>
              </j-vxe-table>
            </a-row>
          </a-col>
          <a-col :md="8" :sm="24">
            <!-- 小组成员 -->
            <a-row :gutter="20" style="margin-bottom: 5px; margin-top: 7px">
              <a-col :span="2">
                <a-button @click="addSmallMember" :disabled="formDisabled || selectedSmallGroupId=='合计'">新增</a-button>
              </a-col>
            </a-row>
            <j-vxe-table
              keep-source
              :ref="refKeys[4]"
              :loading="packagingInboundOrderMemberSmallTable.loading"
              :columns="packagingInboundOrderMemberSmallTable.columns"
              :dataSource="selectedSmallMembers"
              :maxHeight="612"
              :disabled="formDisabled"
              :rowNumber="true"
              :rowSelection="false"
            >
              <template v-slot:action="{ row }">
                <a-popconfirm 
                  title="确认删除?" 
                  @confirm="() => handleMemberRemove(row)"
                  :disabled="formDisabled"
                >
                  <a :disabled="formDisabled">
                    删除
                  </a>
                </a-popconfirm>
              </template>
            </j-vxe-table>
          </a-col>
        </a-row>
      </a-tab-pane>
      <a-tab-pane tab="作业消耗" :key="refKeys[2]" :forceRender="true">
        <!-- 新增按钮-->
        <a-row v-if="!formDisabled">
          <a-col :span="2" style="margin-top:3px">
            <a-button @click="handleAddCard" type="primary" icon="plus">新增</a-button>
          </a-col>
        </a-row>
        <div 
          style="max-height: 600px; 
                  overflow-y: auto; 
                  margin-top: 10px;
                  border: 1px solid #dcdfe6;  /* 添加边框颜色 */
                  border-radius: 4px;         /* 添加圆角 */
                  padding: 10px;              /* 添加内边距 */
                  box-shadow: 0 2px 4px rgba(0,0,0,.1); /* 添加轻微阴影 */
                  margin-bottom: 10px;">
          <el-card v-for="(card, index) in cardList" :key="index"
          style="margin-bottom: 10px;">
            <a-row>
              <a-col :span="6">
                <a-form-model-item label="包装小组" 
                :labelCol="{ xs: { span: 24 }, sm: { span: 4 } }"
                :wrapperCol="{ xs: { span: 24 }, sm: { span: 18 } }"
                >
                  <j-search-select-tag
                    placeholder="请选择包装小组"
                    v-model="card.groupId"
                    :disabled="formDisabled"
                    :dict="`erp_package_group,team_group,id,team_id = \'` + model.packagingTeamId + `\'`" />
                </a-form-model-item>
              </a-col>
              <a-col :span="2" style="margin-top:3px" v-if="!formDisabled">
                <a-button @click="handleDeleteCard(index)" type="danger" icon="delete">删除</a-button>
              </a-col>
            </a-row>
            <a-row>
              <a-col :span="4" style="margin-top:3px" v-if="!formDisabled">
                <a-button @click="addMaterial(index)" icon="plus">新增物料</a-button>
              </a-col>
            </a-row>
            <a-row>
              <!-- 物料列表 -->
              <a-col :span="24">
                <j-vxe-table
                  style="margin: 10px 0"
                  keep-source
                  :ref="'materialItemTable_' + index"
                  :loading="packagingInboundOrderMaterialTable.loading"
                  :columns="packagingInboundOrderMaterialTable.columns"
                  :dataSource="card.materialItems"
                  :maxHeight="300"
                  :disabled="formDisabled"
                  :rowNumber="true"
                  :rowSelection="!formDisabled"
                  :toolbar="true"
                  :toolbarConfig="{
                    slots: ['prefix', 'suffix'],
                    btn: ['remove', 'clearSelection'],
                  }"
                  @remove="(event) => handleDelete(event, index)"
                />
              </a-col>
            </a-row>
          </el-card>
        </div>
      </a-tab-pane>
      <a-tab-pane tab="包装明细" :key="refKeys[3]" :forceRender="true">
        <j-vxe-table
          keep-source
          :ref="refKeys[3]"
          :loading="packagingInboundOrderPacknumTable.loading"
          :columns="packagingInboundOrderPacknumTable.columns"
          :dataSource="showReportPacknumList"
          :maxHeight="600"
          :disabled="formDisabled"
          :rowNumber="true"
          :toolbar="false"
        />
      </a-tab-pane>
    </a-tabs>
    <!-- 作业消耗 -->
    <material-list-modal ref="materialListModal" @ok="selectMaterial" :currentCardIndex="currentCardIndex"/>
    <!-- 变更物料 -->
    <erp-all-goods-list-modal ref="selectGoodsList" @goodRowsOk="goodRowsOk" checkval="radio" />
  </a-spin>
</template>

<script>
import { getAction, postAction, putAction } from '@/api/manage'
import { JVxeTableModelMixin } from '@/mixins/JVxeTableModelMixin.js'
import { JVXETypes } from '@/components/jeecg/JVxeTable'
import { getRefPromise, VALIDATE_FAILED } from '@/components/jeecg/JVxeTable/utils/vxeUtils.js'
import JFormContainer from '@/components/jeecg/JFormContainer'
import MaterialListModal from '../../../pro/modules/MaterialListModal.vue'
import ErpAllGoodsListModal from '@/components/base/modal/ErpAllGoodsListModal.vue'

export default {
  name: 'PackagingWorkForm',
  mixins: [JVxeTableModelMixin],
  components: {
    JFormContainer,
    MaterialListModal,
    ErpAllGoodsListModal,
  },
  data() {
    return {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
      },
      model: {},
      // 新增时子表默认添加几行空数据
      addDefaultRowNum: 1,
      validatorRules: {
        packagingWorkshopCode: [{ required: true, message: '请选择包装车间!' }],
        packagingTeamId: [{ required: true, message: '请选择包装班组!' }],
      },
      iseEdit: false,
      teamlist: [],
      formulalist: [],
      selectedGroupId: '', // 跟踪当前正在编辑的团队（上一次点击的行）
      selectedSmallGroupId: '', 
      selectedMembers: [], // 当前下方表格的编辑数据
      selectedSmallMembers: [],
      allReportPacks: [],
      refKeys: [
        'packagingInboundOrderDetail',
        'packagingInboundOrderSmallDetail',
        'packagingInboundOrderMaterial',
        'packagingInboundOrderPacknum',
        'packagingInboundOrderMember',
      ],
      tableKeys: [
        'packagingInboundOrderDetail',
        'packagingInboundOrderSmallDetail',
        'packagingInboundOrderMaterial',
        'packagingInboundOrderPacknum',
        'packagingInboundOrderMember',
      ],
      activeKey: 'packagingInboundOrderDetail',
      // 包装日报
      packagingInboundOrderGroupTable: {
        loading: false,
        dataSource: [],
        columns: [],
      },
      // 小包装日报
      packagingInboundOrderGroupSmallTable: {
        loading: false,
        dataSource: [],
        columns: [],
      },
      // 作业定额
      packagingInboundOrderQuotaTable: {
        loading: false,
        dataSource: [
          {
            quotaType: '1',
            quotaName: '包装定额'
          },
          {
            quotaType: '2',
            quotaName: '封包定额'
          },
          {
            quotaType: '3',
            quotaName: '码垛定额'
          },
          {
            quotaType: '4',
            quotaName: '叉车定额'
          },
          {
            quotaType: '5',
            quotaName: '其他定额'
          }
        ],
        columns: [],
      },
      // 作业定额 小包装日报
      packagingInboundOrderQuotaSmallTable: {
        loading: false,
        dataSource: [
          {
            quotaType: '1',
            quotaName: '包装定额'
          },
          {
            quotaType: '2',
            quotaName: '封包定额'
          },
          {
            quotaType: '3',
            quotaName: '码垛定额'
          },
          {
            quotaType: '4',
            quotaName: '叉车定额'
          },
          {
            quotaType: '5',
            quotaName: '其他定额'
          }
        ],
        columns: [],
      },
      // 小组成员
      packagingInboundOrderMemberTable: {
        loading: false,
        dataSource: [],
        columns: [
          {
            title: '姓名',
            key: 'realname',
            type: JVXETypes.input,
            placeholder: '请输入${title}',
            defaultValue: '',
          },
          {
            title: '计件工资',
            key: 'pieceWage',
            type: JVXETypes.inputNumber,
            placeholder: '请输入${title}',
            defaultValue: 0,
            validateRules: [
              {
                handler({ cellValue, row, column }, callback, target) {
                  if (cellValue < 0) {
                    callback(false, '${title}不能小于0') 
                  } else {
                    callback(true)
                  }
                },
                message: '${title}不能为负数',
              }
            ],
            precision: 4,
          },
          {
            title: '备注',
            key: 'remark',
            type: JVXETypes.input,
            width: '100px',
            placeholder: '请输入${title}',
            defaultValue: '',
          },
          {
            title: '操作',
            key: 'action',
            type: JVXETypes.slot,
            fixed: 'right',
            width: '80px',
            align: 'center',
            slotName: 'action',
          },
        ],
      },
      // 小组成员 小包装日报
      packagingInboundOrderMemberSmallTable: {
        loading: false,
        dataSource: [],
        columns: [
          {
            title: '姓名',
            key: 'realname',
            type: JVXETypes.input,
            placeholder: '请输入${title}',
            defaultValue: '',
          },
          {
            title: '计件工资',
            key: 'pieceWage',
            type: JVXETypes.inputNumber,
            placeholder: '请输入${title}',
            defaultValue: 0,
            min: 0,
            precision: 4,
          },
          {
            title: '备注',
            key: 'remark',
            type: JVXETypes.input,
            width: '100px',
            placeholder: '请输入${title}',
            defaultValue: '',
          },
          {
            title: '操作',
            key: 'action',
            type: JVXETypes.slot,
            fixed: 'right',
            width: '80px',
            align: 'center',
            slotName: 'action',
          },
        ],
      },
      // 作业消耗
      packagingInboundOrderMaterialTable: {
        loading: false,
        dataSource: [],
        columns: [
          {
            title: '单据类型',
            key: 'documentType_dictText',
            type: JVXETypes.normal,
            defaultValue: '',
          },
          {
            title: '物料编码',
            key: 'materialCode',
            type: JVXETypes.normal,
            defaultValue: '',
          },
          {
            title: '物料名称',
            key: 'materialName',
            type: JVXETypes.normal,
            defaultValue: '',
          },
          {
            title: '规格型号',
            key: 'specificationModel',
            type: JVXETypes.normal,
            defaultValue: '',
          },
          {
            title: '单位',
            key: 'unit',
            dictCode: 'ji_unit',
            type: JVXETypes.select,
            defaultValue: '',
          },
          {
            title: '库存数量',
            key: 'quantity',
            type: JVXETypes.normal,
            defaultValue: '',
          },
          {
            title: '物料批号',
            key: 'materialBatchNumber',
            type: JVXETypes.normal,
            defaultValue: '',
          },
          {
            title: '生产日期',
            key: 'productionDate',
            type: JVXETypes.normal,
            defaultValue: '',
          },
          {
            title: '限用日期',
            key: 'expirationDate',
            type: JVXETypes.normal,
            defaultValue: '',
          },
          {
            title: '使用数量',
            key: 'consumeQuantity',
            type: JVXETypes.inputNumber,
            defaultValue: '',
          },
        ],
      },
      // 包装明细
      packagingInboundOrderPacknumTable: {
        loading: false,
        dataSource: [],
        columns: [
          {
            title: '订单编号',
            key: 'orderCode',
            type: JVXETypes.normal,
            align: 'center',
            minWidth: '120px',
            defaultValue: '',
          },
          {
            title: '客户物料编码',
            key: 'customerMaterialCode',
            type: JVXETypes.normal,
            align: 'center',
            minWidth: '140px',
            defaultValue: '',
          },
          {
            title: '物料编码',
            key: 'materialCode',
            type: JVXETypes.normal,
            align: 'center',
            minWidth: '140px',
            defaultValue: '',
          },
          {
            title: '物料名称',
            key: 'materialName',
            type: JVXETypes.normal,
            align: 'center',
            minWidth: '200px',
            defaultValue: '',
          },
          {
            title: '规格型号',
            key: 'specificationModel',
            type: JVXETypes.normal,
            align: 'center',
            minWidth: '200px',
            defaultValue: '',
          },
          {
            title: '单位',
            key: 'unit',
            type: JVXETypes.select,
            disabled: true,
            dictCode: 'ji_unit',
            align: 'center',
            minWidth: '120px',
            defaultValue: '',
          },
          {
            title: '物料批号',
            key: 'materialBatchNumber',
            type: JVXETypes.normal,
            align: 'center',
            minWidth: '200px',
            defaultValue: '',
          },
          {
            title: '包装小组',
            key: 'groupName',
            type: JVXETypes.normal,
            align: 'center',
            minWidth: '150px',
            fixed: 'right',
            defaultValue: '',
          },
          {
            title: '包装数量',
            key: 'packageQuantity',
            type: JVXETypes.normal,
            align: 'center',
            minWidth: '150px',
            fixed: 'right',
            defaultValue: '',
          },
        ],
      },
      url: {
        add: '/wms/packaging-inbound-order/add',
        queryById: '/pro/packagingInboundOrder/queryById',
        teamlist: '/packageteam/erpPackageTeam/queryTeamByMainId',
        teamInfo: '/packageteam/erpPackageTeam/queryById',
        grouplist: '/packagegroup/erpPackageGroup/queryGroupMemberByMainId',
        packagingInboundOrderGroup: {
          list: '/wms/packaging-inbound-order/queryPackagingInboundOrderGroupListByMainId',
        },
        packagingInboundOrderItem: {
          list: '/wms/packaging-inbound-order/queryPackagingInboundOrderItemByMainId',
        },
        packagingInboundOrderPackageMaterial: {
          list: '/packaginginboundmaterial/packagingInboundOrderMaterial/queryPackagingInboundOrderMemberByMainId',
        },
        packagingInboundOrderMaterialGroup: {
          list: '/wms/packaging-inbound-order/queryPackagingInboundOrderConsumeGroupListByMainId',
        },
        // 获取物料的定额
        getMaterialQuotaList: '/tslpropackagequota/tslProPackageQuota/list',
        // 获取物料存储仓库
        getGoodList: '/base/erpGoods/list',
      },
      // 存储所有卡片数据
      cardList: [
        // {
        //   groupId: null,
        //   materialItems: [] // 物料数据
        // }
      ],
      // 当前卡片索引
      currentCardIndex: 0,
      // 包装车间字典下拉
      dictOptions:[],
      // 物料动态列头
      materialColumns: [],
      // 动态列头加载完毕标识
      ifFenerateColumns: false,
      ifChangeMaterial: false,
      // 包装明细展示列表
      showReportPacknumList: [],
      // 作业定额初始化后的数据
      materialQuotaList: [],
      // 包装日报包装物料
      packageMaterialList: [],
      // 小包装日报包装物料
      packageMaterialSmallList: [],
    }
  },
  props: {
    //表单禁用
    disabled: {
      type: Boolean,
      default: false,
      required: false,
    },
    customFormData: {
      type: Object,
      default: () => {
        return {}
      },
      required: false,
    },
  },
  computed: {
    formDisabled() {
      return this.disabled
    },
  },
  created() {
    this.loadshopDict();
  },
  methods: {
    // 加载车间字典
    loadshopDict(){
      getAction(`/sys/dict/getDictItems/erp_package_execution_organization,organization_name,organization_code`,{}).then(res=>{
        if(res.success){
          this.dictOptions = res.result.map(item => ({value: item.value, text: item.text}))
        } else {
          this.dictOptions = []
        }
      })
    },
    // 新增作业消耗物料
    addMaterial(index) {
      this.currentCardIndex = index;
      // 打开物料列表弹窗，传递生产车间
      this.$refs.materialListModal.add({
        packshopCode: this.model.packagingWorkshopCode,
      })
    },
    // 选择消耗物料
    selectMaterial(selectedMaterials) {
      if (selectedMaterials && selectedMaterials.length > 0) {
        selectedMaterials.forEach((item) => {
          item.documentType_dictText = '包装消耗';
          item.documentType = 12;
          item.inventoryId = item.id;
          this.cardList[this.currentCardIndex].materialItems.push(item)
        })
      }
    },
    addBefore() {
      this.packagingInboundOrderGroupTable.dataSource = []
      this.packagingInboundOrderMaterialTable.dataSource = []
      this.packagingInboundOrderPacknumTable.dataSource = []
      this.showReportPacknumList = []
      this.selectedMembers = []
    },
    add(record) {
      this.model = Object.assign({}, record);
      this.model.inventoryId = record.id;
      this.model.inventoryRecordQuantity = record.quantity;
      this.materialColumns.push(record);
      this.model.oldMaterialCode = record.materialCode;
      this.model.isReplaced = 0;
      // 物料信息
      this.packageMaterialList.push(JSON.parse(JSON.stringify(record)));
      this.packageMaterialList[0].workType = '1'
      this.packageMaterialSmallList.push(JSON.parse(JSON.stringify(record)));
      this.packageMaterialSmallList[0].workType = '2'
      this.generateColumns();
      this.iseEdit = false
      // 查询物料存储仓库
      this.getGoodList();
      // 暂无默认包装车间
      // this.getItemList(record.packshopCode)
    },
    getGoodList(){
      getAction(this.url.getGoodList, { code: this.model.materialCode, name: this.model.materialName }).then((res) => {
          if (res.success) {
            if(res.result.records?.length > 0){
              this.model.warehouseCode = res.result.records[0].warehouseCode;
            }
          }
        })
    },
    getItemList(packshopCode){
      if(packshopCode == null || packshopCode == undefined || packshopCode == ''){
        this.teamlist = []
      }else {
        getAction(this.url.teamlist, { departCode: packshopCode }).then((res) => {
          if (res.success) {
            this.teamlist = res.result
          }
        })
      }
    },
    // 处理子列输入变化
    handleChildInput(row, rowIndex, fieldName, materialCode) {
      // 计算当前行金额
      this.calculateRowAmount(row);
      // 如果是工种为1的行，更新工种为3的行
      if (row.groupType === '1') {
        this.updateType3Rows(fieldName, materialCode);
      }
      // 更新 包装明细 的包装数量
      this.savePackageNum(row, fieldName, materialCode, row[fieldName]);
      // 计算金额合计
      this.calculateTotalAmount(); 
    },
    handleQuotaInput(rowIndex) {
      let tableRef = this.activeKey === this.refKeys[1]
          ? 'packagingInboundOrderGroupSmallTable' 
          : 'packagingInboundOrderGroupTable';
      // 当作业定额输入变化时，重新计算定额类型对应行的金额
      this[tableRef].dataSource.forEach(row => {
        if(row.groupType == rowIndex+1){
          this.calculateRowAmount(row);
        }
      });
      // 计算金额合计
      this.calculateTotalAmount(); 
    },
    updateType3Rows(fieldName, materialCode) {
      let tableRef = this.activeKey === this.refKeys[1]
          ? 'packagingInboundOrderGroupSmallTable' 
          : 'packagingInboundOrderGroupTable';
      // 计算工种为1的总和
      const type1Sum = this[tableRef].dataSource
        .filter(item => item.groupType === '1')
        .reduce((sum, item) => {
          const value = parseFloat(item[fieldName]) || 0;
          return sum + value;
        }, 0);
      // 更新所有工种为3的行
      this[tableRef].dataSource
        .filter(item => item.groupType === '3' || (item.groupName === '合计' && item.groupType === ''))
        .forEach(item => {
          item[fieldName] = type1Sum;
          // 确保金额也更新
          this.calculateRowAmount(item);
          // 更新 包装明细 的包装数量
          this.savePackageNum(item, fieldName, materialCode, type1Sum);
        });
    },
    // 更新包装明细的包装数量
    savePackageNum(row, fieldName, materialCode, packageQuantity){
      // 选择小组时，在‘包装明细’中显示小组每个物料的包装明细
      if(this.packagingInboundOrderPacknumTable.dataSource?.length > 0){
        if(this.activeKey != this.refKeys[1]){
          // 包装日报
          this.packagingInboundOrderPacknumTable.dataSource
          .filter(item => item.groupId === row.groupId && item.materialCode === materialCode
          && item.workType === '1')
          .map((item) =>{
            item.packageQuantity = packageQuantity
          });
        }else {
          // 小包装日报
          this.packagingInboundOrderPacknumTable.dataSource
            .filter(item => item.groupId === row.groupId && item.materialCode === materialCode
            && item.workType === '2')
            .map((item) =>{
              item.packageQuantity = packageQuantity
            });
        }
      }
    },
    // 计算金额
    calculateRowAmount(row) {
      let totalAmount = 0;
      // 根据当前行的工种类型，找到作业定额表格中对应类型的那一行
      let quotaTypeIndex = -1;
      switch (row.groupType) {
        case '1': // 包装 -> 包装定额（第一行）
          quotaTypeIndex = 0;
          break;
        case '2': // 封包 -> 封包定额（第二行）
          quotaTypeIndex = 1;
          break;
        case '3': // 码垛 -> 码垛定额（第三行）
          quotaTypeIndex = 2;
          break;
        case '4': // 叉车 -> 叉车定额（第四行）
          quotaTypeIndex = 3;
          break;
        case '5': // 其他 -> 其他定额（第五行）
          quotaTypeIndex = 4;
          break;
        default:
          quotaTypeIndex = -1;
      }
      if (quotaTypeIndex === -1) {
        row.amount = '0.0000';
        return;
      }
      const quotaRow = this.activeKey === this.refKeys[1]?this.packagingInboundOrderQuotaSmallTable.dataSource[quotaTypeIndex]:this.packagingInboundOrderQuotaTable.dataSource[quotaTypeIndex];
      // 遍历每个动态列
      this.materialColumns.forEach(item => {
        const key = `${item.materialName}_+_${item.materialCode}`;
        const quantity = parseFloat(row[key]) || 0;
        const quotaValue = parseFloat(quotaRow[key]) || 0; // 定额金额
        totalAmount += quantity * quotaValue;
      });
      // 确保金额是有效数字
      row.amount = isNaN(totalAmount) ? '0.0000' : totalAmount.toFixed(4);
      // 将金额平均分配到小组成员
      this.distributeAmountToMembers(row);
    },
    // 计算金额列的合计
    calculateTotalAmount() {
      let tableRef = this.activeKey === this.refKeys[1]
          ? 'packagingInboundOrderGroupSmallTable' 
          : 'packagingInboundOrderGroupTable';
      // 找到合计行（我们约定合计行的groupName和groupType都是空字符串）
      const totalRow = this[tableRef].dataSource.find(
        item => item.groupName === '合计' && item.groupType === ''
      );
      if (!totalRow) return;
      // 计算所有非合计行的金额之和
      let totalAmount = 0;
      this[tableRef].dataSource.forEach(item => {
        // 跳过合计行
        if (item.groupName !== '合计' || item.groupType !== '') {
          const amount = parseFloat(item.amount) || 0;
          totalAmount += amount;
        }
      });
      // 更新合计行的金额
      totalRow.amount = totalAmount.toFixed(4);
    },
    // 将金额平均分配到小组成员
    distributeAmountToMembers(row) {
      if (!row.erpPackageGroupMemberList || row.erpPackageGroupMemberList.length === 0) return;
      const amount = parseFloat(row.amount) || 0;
      const memberCount = row.erpPackageGroupMemberList.length;
      // 处理除数为0的情况
      const average = memberCount > 0 ? amount / memberCount : 0;
      this.saveCurrentMembersToTeam()
      this.saveSmallCurrentMembersToTeam()
      row.erpPackageGroupMemberList.forEach(member => {
        if(row.groupId == member.groupId){
          // 确保分配的值是有效数字
          member.pieceWage = (isNaN(average) ? 0 : average).toFixed(4);
        }
      });
      // 更新表格显示
      this.$forceUpdate();
    },
    // 生成动态列
    generateColumns() {
      // 包装日报
      let baseGroupColumns = [
        {
          title: '小组',
          key: 'groupName',
          type: JVXETypes.normal,
          width: '150px',
          align: 'center',
          fixed: 'left',
          rowspan: 2 // 跨两行
        },
        {
          title: '作业工种',
          key: 'groupType',
          dictCode: 'package_job_type',
          type: JVXETypes.select,
          disabled: true,
          width: '150px',
          align: 'center',
          fixed: 'left',
          rowspan: 2
        },
      ]
      // 作业定额
      let baseQuotaColumns = [
        {
          title: '定额类型',
          key: 'quotaName',
          type: JVXETypes.normal,
          width: '360px',
          align: 'center',
          fixed: 'left',
          rowspan: 2 // 跨两行
        },
      ]
      // 包装日报
      let dynamicGroupColumns = [...baseGroupColumns]
      let dynamicQuotaColumns = [...baseQuotaColumns]
      this.materialColumns.forEach((item) => {
        // 包装日报 增加动态列
        dynamicGroupColumns.push(
          {
            title: item.materialCode,
            key: item.materialCode,
            align: 'center',
            headerSlots: { title: 'parentHeader' }, // 父列使用自定义标题插槽
            children: [  // 子列定义
              {
                title: item.materialName,
                key: item.materialName + '_+_' + item.materialCode,
                width: '200px',
                align: 'center',
                type: JVXETypes.html, // 使用HTML类型实现自定义渲染
                slots: {
                  default: item.materialName + '_+_' + item.materialCode// 使用自定义单元格插槽
                },
              }
            ]
          },
        );
        // 作业定额 增加动态列
        dynamicQuotaColumns.push(
          {
            title: item.materialCode,
            key: item.materialCode,
            align: 'center',
            headerSlots: { title: 'parentHeaderQuota' }, // 父列使用自定义标题插槽
            children: [  // 子列定义
              {
                title: item.materialName,
                key: item.materialName + '_+_' + item.materialCode,
                width: '200px',
                align: 'center',
                type: JVXETypes.html, // 使用HTML类型实现自定义渲染
                slots: {
                  default: item.materialName + '_+_' + item.materialCode// 使用自定义单元格插槽
                },
              }
            ]
          },
        );
      });
      let amountGroupColumns = 
        {
          title: '金额',
          key: 'amount',
          type: JVXETypes.normal,
          minWidth: '120px',
          align: 'center',
          fixed: 'right',
          rowspan: 2,
          defaultValue: '',
          min: 0,
          formatter: (value) => parseFloat(value).toFixed(4)
        };
      let remarkGroupColumns = 
        {
          title: '备注',
          key: 'remark',
          type: JVXETypes.html,
          minWidth: '150px',
          align: 'center',
          fixed: 'right',
          rowspan: 2,
          placeholder: '请输入',
          defaultValue: '',
          slots: {
            default: 'remark_column' // 使用自定义插槽
          }
        };
      dynamicGroupColumns.push(amountGroupColumns)
      dynamicGroupColumns.push(remarkGroupColumns)
      // 给作业日报动态列赋值
      this.packagingInboundOrderGroupTable.columns = dynamicGroupColumns;
      this.packagingInboundOrderQuotaTable.columns = dynamicQuotaColumns;
      // 给小作业日报动态列赋值
      this.packagingInboundOrderGroupSmallTable.columns = dynamicGroupColumns;
      this.packagingInboundOrderQuotaSmallTable.columns = dynamicQuotaColumns;

      // 作业定额列表 获取定额
      if(!this.iseEdit){
        this.getMaterialQuotaList(this.materialColumns[0].materialCode);
      }
      this.ifFenerateColumns = true
    },
    // 获取物料定额列表
    getMaterialQuotaList(materialCode){
      getAction(this.url.getMaterialQuotaList, { materialCode: materialCode }).then((res) => {
        if (res.success) {
          res.result.records.forEach((item) =>{
            this.$set(this.packagingInboundOrderQuotaTable.dataSource[0], item.materialName + '_+_' + item.materialCode, item.packageQuota);
            this.$set(this.packagingInboundOrderQuotaTable.dataSource[1], item.materialName + '_+_' + item.materialCode, item.envelopeQuota);
            this.$set(this.packagingInboundOrderQuotaTable.dataSource[2], item.materialName + '_+_' + item.materialCode, item.palletizingQuota);
            this.$set(this.packagingInboundOrderQuotaTable.dataSource[3], item.materialName + '_+_' + item.materialCode, item.forkliftQuota);
            this.$set(this.packagingInboundOrderQuotaTable.dataSource[4], item.materialName + '_+_' + item.materialCode, item.otherQuota); 
          })
          this.materialQuotaList = JSON.parse(JSON.stringify(this.packagingInboundOrderQuotaTable.dataSource))
          this.packagingInboundOrderQuotaSmallTable.dataSource = JSON.parse(JSON.stringify(this.packagingInboundOrderQuotaTable.dataSource))
        }
      })
    },
    edit(record) {
      this.iseEdit = true
      this.model = Object.assign({}, record);
      this.getItemList(this.model.packagingWorkshopCode)
      // 包装日报：包装日报表格，包装小组信息
      getAction(this.url.packagingInboundOrderGroup.list, { id: this.model.id }).then((res) => {
        if (res.success) {
          // 包装日报
          this.packagingInboundOrderGroupTable.dataSource = res.result.filter(item => item.workType === '1')
          .map(item => ({
            ...item,
            erpPackageGroupMemberList: item.packagingInboundOrderGroupMemberList.map(item => ({
              ...item,
              member: item.memberName,
              realname: item.memberName,
              pieceWage: item.wage,
            }))
          }))
          // 小包装日报
          this.packagingInboundOrderGroupSmallTable.dataSource = res.result.filter(item => item.workType === '2')
          .map(item => ({
            ...item,
            erpPackageGroupMemberList: item.packagingInboundOrderGroupMemberList.map(item => ({
              ...item,
              member: item.memberName,
              realname: item.memberName,
              pieceWage: item.wage,
            }))
          }))
          if(res.result?.length>0){
            // 物料包装数量信息
            getAction(this.url.packagingInboundOrderItem.list, { id: this.model.id }).then((res) => {
              if (res.success) {
                this.packagingInboundOrderPacknumTable.dataSource = res.result
                // 包装日报/小包装日报 分别增加合计行
                this.getNumTotalLine('1');
                this.getNumTotalLine('2');
              }
            })
            // 包装小组成员信息-确保成员计件工资是数字
            this.selectedMembers = 
              JSON.parse(JSON.stringify(
                (this.packagingInboundOrderGroupTable.dataSource[0]?.erpPackageGroupMemberList || [])
                .map(member => {
                  member.pieceWage = (parseFloat(member.pieceWage) || 0);
                  return member;
                })
              ));
            this.selectedSmallMembers = 
              JSON.parse(JSON.stringify(
                (this.packagingInboundOrderGroupSmallTable.dataSource[0]?.erpPackageGroupMemberList || [])
                .map(member => {
                  member.pieceWage = (parseFloat(member.pieceWage) || 0);
                  return member;
                })
              ));
          }
        }
      })
      //作业定额(包装物料信息)
      getAction(this.url.packagingInboundOrderPackageMaterial.list, { id: this.model.id , pageSize: 100}).then((res) => {
        if (res.success) {
          if(res.result?.length>0){
            this.model.packagingInboundOrderMaterialList = JSON.parse(JSON.stringify(res.result));
            // 获取动态列表
            this.materialColumns = res.result.filter(item => item.workType === '1');
            this.generateColumns();
            res.result.filter(item => item.workType === '1')
            .forEach((item) =>{
              this.$set(this.packagingInboundOrderQuotaTable.dataSource[0], item.materialName + '_+_' + item.materialCode, item.packageQuota);
              this.$set(this.packagingInboundOrderQuotaTable.dataSource[1], item.materialName + '_+_' + item.materialCode, item.envelopeQuota);
              this.$set(this.packagingInboundOrderQuotaTable.dataSource[2], item.materialName + '_+_' + item.materialCode, item.palletizingQuota);
              this.$set(this.packagingInboundOrderQuotaTable.dataSource[3], item.materialName + '_+_' + item.materialCode, item.forkliftQuota);
              this.$set(this.packagingInboundOrderQuotaTable.dataSource[4], item.materialName + '_+_' + item.materialCode, item.otherQuota); 
            })
            res.result.filter(item => item.workType === '2')
            .forEach((item) =>{
              this.$set(this.packagingInboundOrderQuotaSmallTable.dataSource[0], item.materialName + '_+_' + item.materialCode, item.packageQuota);
              this.$set(this.packagingInboundOrderQuotaSmallTable.dataSource[1], item.materialName + '_+_' + item.materialCode, item.envelopeQuota);
              this.$set(this.packagingInboundOrderQuotaSmallTable.dataSource[2], item.materialName + '_+_' + item.materialCode, item.palletizingQuota);
              this.$set(this.packagingInboundOrderQuotaSmallTable.dataSource[3], item.materialName + '_+_' + item.materialCode, item.forkliftQuota);
              this.$set(this.packagingInboundOrderQuotaSmallTable.dataSource[4], item.materialName + '_+_' + item.materialCode, item.otherQuota); 
            })
            this.packageMaterialList = res.result.filter(item => item.workType === '1');
            this.packageMaterialSmallList = res.result.filter(item => item.workType === '2');
          }
        }
      })
      // 作业消耗
      getAction(this.url.packagingInboundOrderMaterialGroup.list, { id: this.model.id }).then(res => {
        if (res.success && res.result) {
          this.cardList = res.result.map(item => ({
            ...item,
            materialItems: item.packagingInboundOrderConsumeMaterialList || []
          }));
        }
      });
    },
    // 获取合计行
    getNumTotalLine(type){
      let tableRef = type === '2'
          ? 'packagingInboundOrderGroupSmallTable' 
          : 'packagingInboundOrderGroupTable';
      // 配置合计行
      let numTotal = JSON.parse(JSON.stringify(this[tableRef].dataSource[0]))
      numTotal.id = '合计'
      numTotal.groupId = '合计'
      numTotal.groupName = '合计'
      numTotal.groupType = ''
      numTotal.amount = 0.0000
      numTotal.remark = null
      // 计算金额总和（所有行）
      let totalAmount = 0;
      if(this[tableRef].dataSource?.length>0){
        this[tableRef].dataSource.forEach((item) =>{
          // 累加金额（排除即将添加的合计行）
          totalAmount += parseFloat(item.amount) || 0;
          this.packagingInboundOrderPacknumTable.dataSource.filter(material => material.workType === type).forEach((material) =>{

            if(material.groupId == item.groupId){                                 
              this.$set(item, material.materialName + '_+_' + material.materialCode, material.packageQuantity);
              // 如果是groupType为1(包装)的行，累加到合计行
              if(item.groupType === '1') {
                const key = material.materialName + '_+_' + material.materialCode;
                const currentValue = parseFloat(numTotal[key]) || 0;
                numTotal[key] = currentValue + (parseFloat(item[key]) || 0);
              }
            }
          })
        })
        // 设置金额总和
        numTotal.amount = totalAmount.toFixed(4);
        // 添加合计行
        this[tableRef].dataSource.push(numTotal);
      }
    },
    cleanDataSource(){
      this.packagingInboundOrderGroupTable.dataSource = []
      this.packagingInboundOrderGroupSmallTable.dataSource = []
      this.selectedMembers = []
      this.selectedSmallMembers = []
      this.packagingInboundOrderQuotaTable.dataSource = JSON.parse(JSON.stringify(this.materialQuotaList))
      this.packagingInboundOrderQuotaSmallTable.dataSource = JSON.parse(JSON.stringify(this.materialQuotaList))
    },
    handlePackshopChange(){
      this.model.packagingTeamId = null
      this.getItemList(this.model.packagingWorkshopCode)
      this.cleanDataSource()
    },
    // 合并处理班组变更和校验
    handleTeamChangeAndValidate(value) {
      this.handleTeamChange(value); // 原有逻辑
      this.$nextTick(() => {
        // 主动触发packagingTeamId字段的校验
        this.$refs.form.validateField('packagingTeamId');
      });
    },
    handleTeamChange() {
      this.cleanDataSource()
      getAction(this.url.grouplist, { teamId: this.model.packagingTeamId }).then((res) => {
        if (res.success && res.result) {
          let materialList = []
          res.result.forEach((item) => {
            item.groupId = item.id
            item.groupName = item.teamGroup
            this.$set(item, 'remark', null)
            this.model.team = item.team
            if (item.erpPackageGroupMemberList) {
              item.erpPackageGroupMemberList.forEach((sons) => {
                sons.realname = sons.member
              })
            }
            // 包装日报 初始化数据
            if (this.materialColumns?.length > 0) {
              this.materialColumns.forEach(material => {
                let materialItem = material;
                // 初始化动态列数据
                this.$set(item, materialItem.materialName+'_+_'+materialItem.materialCode, null);
                // 初始化包装明细数据-包装日报
                materialItem = {
                  ...material,
                  groupId: item.groupId,
                  groupName: item.groupName,
                  groupType: item.groupType,
                  packageQuantity: 0,
                  workType: '1',
                }
                materialList.push(materialItem)
                // 小包装日报 初始化数据
                let materialSmallItem = JSON.parse(JSON.stringify(materialItem));
                materialSmallItem.workType = '2';
                materialList.push(materialSmallItem)
              });
            }
          })
          // 添加合计行
          if(res.result?.length > 0){
            let numTotal = JSON.parse(JSON.stringify(res.result[0]))
            numTotal.id = '合计'
            numTotal.groupId = '合计'
            numTotal.groupName = '合计'
            numTotal.groupType = ''
            numTotal.amount = 0.0000
            res.result.push(numTotal);
          }
          // 包装日报、小组成员初始化
          this.packagingInboundOrderGroupTable.dataSource = JSON.parse(JSON.stringify(res.result)) || []
          this.selectedMembers = JSON.parse(JSON.stringify(res.result[0].erpPackageGroupMemberList)) || []
          this.selectedGroupId = res.result[0].id
          // 小包装日报、小组成员初始化
          this.packagingInboundOrderGroupSmallTable.dataSource = JSON.parse(JSON.stringify(res.result)) || []
          this.selectedSmallMembers = JSON.parse(JSON.stringify(res.result[0].erpPackageGroupMemberList)) || []
          this.selectedSmallGroupId = res.result[0].id
          // 包装明细列表初始化
          this.packagingInboundOrderPacknumTable.dataSource = materialList
        }
      })
    },
    handleRowClick(event) {
      const rowElement = event.target.closest('tr');
      if (!rowElement) return;
      // 获取行索引
      const rowIndex = [...rowElement.parentNode.children].indexOf(rowElement); // 减去表头行
      // 通过索引获取行数据
      if (rowIndex >= 0 && this.packagingInboundOrderGroupTable.dataSource[rowIndex]) {
        const rowData = this.packagingInboundOrderGroupTable.dataSource[rowIndex];
        // 保存当前编辑的成员数据到原团队
        if (this.selectedGroupId) {
          this.saveCurrentMembersToTeam();
        }
        // 更新选中的小组ID
        this.selectedGroupId = rowData.groupId;
        // 更新小组成员
        this.selectedMembers = this.selectedGroupId=='合计'?[]:[...(JSON.parse(JSON.stringify(rowData.erpPackageGroupMemberList)) || [])];
        // 更新包装明细显示
        this.showReportPacknumList = this.packagingInboundOrderPacknumTable.dataSource?.filter(
          item => item.groupId === this.selectedGroupId && item.workType === '1'
        ) || [];
      }
    },
    // 保存当前编辑的成员数据到原团队
    saveCurrentMembersToTeam() {
      if (!this.selectedGroupId) return
      const teamIndex = this.packagingInboundOrderGroupTable.dataSource.findIndex(
        (item) => item.groupId === this.selectedGroupId
      )
      if (teamIndex !== -1) {
        // 直接更新原团队的成员数据（selectedMembers 已包含用户编辑后的值）
        this.$set(
          this.packagingInboundOrderGroupTable.dataSource[teamIndex],
          'erpPackageGroupMemberList',
          this.selectedMembers
        )
      }
    },
    addMember() {
      this.saveCurrentMembersToTeam();
      this.selectedMembers.push({
        realname: '',
        pieceWage: 0,
        usercode: '',
        remark: '',
        _checked: false,
        groupId: this.selectedGroupId,
      })
    },
    handleSmallRowClick(event) {
      const rowElement = event.target.closest('tr');
      if (!rowElement) return;
      // 获取行索引
      const rowIndex = [...rowElement.parentNode.children].indexOf(rowElement); // 减去表头行
      // 通过索引获取行数据
      if (rowIndex >= 0 && this.packagingInboundOrderGroupSmallTable.dataSource[rowIndex]) {
        const rowData = this.packagingInboundOrderGroupSmallTable.dataSource[rowIndex];
        // 保存当前编辑的成员数据到原团队
        if (this.selectedSmallGroupId) {
          this.saveSmallCurrentMembersToTeam();
        }
        // 更新选中的小组ID
        this.selectedSmallGroupId = rowData.groupId;
        // 更新小组成员
        this.selectedSmallMembers = this.selectedSmallGroupId=='合计'?[]:[...(JSON.parse(JSON.stringify(rowData.erpPackageGroupMemberList)) || [])];
        // 更新包装明细显示
        this.showReportPacknumList = this.packagingInboundOrderPacknumTable.dataSource?.filter(
          item => item.groupId === this.selectedSmallGroupId && item.workType === '2'
        ) || [];
      }
    },
    // 保存当前编辑的成员数据到原团队
    saveSmallCurrentMembersToTeam() {
      if (!this.selectedSmallGroupId) return
      const teamIndex = this.packagingInboundOrderGroupSmallTable.dataSource.findIndex(
        (item) => item.groupId === this.selectedSmallGroupId
      )
      if (teamIndex !== -1) {
        // 直接更新原团队的成员数据（selectedMembers 已包含用户编辑后的值）
        this.$set(
          this.packagingInboundOrderGroupSmallTable.dataSource[teamIndex],
          'erpPackageGroupMemberList',
          this.selectedSmallMembers
        )
      }
    },
    addSmallMember() {
      this.saveSmallCurrentMembersToTeam();
      this.selectedSmallMembers.push({
        realname: '',
        pieceWage: 0,
        usercode: '',
        remark: '',
        _checked: false,
        groupId: this.selectedSmallGroupId,
      })
    },
    // 删除小组成员
    handleMemberRemove(key) {
      let tableRef = this.activeKey === this.refKeys[1]
          ? 'selectedSmallMembers' 
          : 'selectedMembers';
      const dataSource = [...this[tableRef]]
      this[tableRef] = dataSource.filter((item) => item.id !== key.id)
    },
    // 提交保存
    async handleOk() {
      this.saveCurrentMembersToTeam() 
      this.saveSmallCurrentMembersToTeam()// 保存最后一次编辑的团队数据
      //  校验主表单
      const mainFormValid = await new Promise((resolve) => {
        this.$refs.form.validate((valid) => resolve(valid))
      })
      if (!mainFormValid) return
      this.confirmLoading = true
      // 包装日报
      const mainData = this.packagingInboundOrderGroupTable.dataSource
        .filter(item => item.groupName !== '合计')
        .map(item => ({ ...item, workType: '1' }));
      // 小包装日报
      const smallData = this.packagingInboundOrderGroupSmallTable.dataSource
        .filter(item => item.groupName !== '合计')
        .map(item => ({ ...item, workType: '2' }));
      // 合并包装日报和小包装日报数据
      const mergedData = [...mainData, ...smallData];
      // 小组信息
      this.model.packagingInboundOrderGroupList = mergedData.map((item) => ({
        ...item,
        packagingInboundOrderGroupMemberList: item.erpPackageGroupMemberList.map(item => ({
          ...item,
          memberName: item.realname || item.member,
          wage: item.pieceWage,
          id: null,
          createTime: null,
          updateTime: null
        }))
      }))
      // 物料作业数量
      this.model.packagingInboundOrderItemList = [];
      // 包装物料信息
      this.model.packagingInboundOrderMaterialList = [];
      if(mainData?.length>0 && smallData?.length>0 && this.packageMaterialList?.length>0 && this.packageMaterialSmallList?.length>0){
        // 包装日报-物料作业数量赋值
        this.getPackageNum(mainData, '1');
        // 小包装日报-物料作业数量赋值
        this.getPackageNum(smallData, '2');
      }
      // 包装物料信息赋值
      this.model.packagingInboundOrderMaterialList = [...this.packageMaterialList, ...this.packageMaterialSmallList];
      // 计算包装总数量
      this.calculatePackageTotalQuantity();
      // 作业消耗
      this.model.packagingInboundOrderConsumeGroupList = this.cardList.map((item) => ({
        ...item,
        id: null,
        packshopCode: this.model.packagingWorkshopCode,
        teamId: this.model.packagingTeamId,
        packagingInboundOrderConsumeMaterialList: item.materialItems.map(item => ({
          ...item,
          id: null,
          createTime: null,
          updateTime: null
        }))
      }))
      if(undefined == this.model.packageTotalQuantity || null == this.model.packageTotalQuantity || this.model.packageTotalQuantity <= 0){
        this.$message.warning('包装作业数量不能为0!')
        this.confirmLoading = false
        return;
      }
      await postAction(this.url.add, this.model).then((res)=>{
        if(res.success){
          this.$message.success(res.message);
          this.$emit('ok');
        }else{
          this.$message.warning(res.message);
        }
      }).finally(() => {
        this.confirmLoading = false;
      })
    },
    getPackageNum(packageList, type){
      let materialList = type === '1'
          ? 'packageMaterialList' 
          : 'packageMaterialSmallList';
      let QuotaTable = type === '1'
          ? 'packagingInboundOrderQuotaTable' 
          : 'packagingInboundOrderQuotaSmallTable';
      this[materialList].forEach((material) =>{
        packageList.forEach((item) =>{
          this.model.packagingInboundOrderItemList.push(
            {
              ...material,
              orderCode: material.orderNumber,
              groupId: item.groupId,
              groupName: item.groupName,
              groupType: item.groupType,
              packageQuantity: item[material.materialName+'_+_'+material.materialCode]
            }
          )
        })
        // 作业定额-存到物料信息中
        material.packageQuota = this[QuotaTable].dataSource[0][material.materialName+'_+_'+material.materialCode]
        material.envelopeQuota = this[QuotaTable].dataSource[1][material.materialName+'_+_'+material.materialCode]
        material.palletizingQuota = this[QuotaTable].dataSource[2][material.materialName+'_+_'+material.materialCode]
        material.forkliftQuota = this[QuotaTable].dataSource[3][material.materialName+'_+_'+material.materialCode]
        material.otherQuota = this[QuotaTable].dataSource[4][material.materialName+'_+_'+material.materialCode]
        material.createTime = null
      })
    },
    // 新增方法：计算包装总数量
    calculatePackageTotalQuantity() {
      let total = 0;
      // 计算包装日报的合计
      const largeTotalRow = this.packagingInboundOrderGroupTable.dataSource.find(
        row => row.groupName === '合计' && row.groupType === ''
      );
      if (largeTotalRow) {
        this.materialColumns.forEach(item => {
          const key = `${item.materialName}_+_${item.materialCode}`;
          total += parseFloat(largeTotalRow[key] || 0);
        });
      }
      // 计算小包装日报的合计
      const smallTotalRow = this.packagingInboundOrderGroupSmallTable.dataSource.find(
        row => row.groupName === '合计' && row.groupType === ''
      );
      if (smallTotalRow) {
        this.materialColumns.forEach(item => {
          const key = `${item.materialName}_+_${item.materialCode}`;
          total += parseFloat(smallTotalRow[key] || 0);
        });
      }
      // 赋值给包装总数
      this.model.packageTotalQuantity = total;
    },
    getAllTable() {
      let values = this.tableKeys.map((key) => getRefPromise(this, key))
      return Promise.all(values)
    },
    //校验所有一对一子表表单
    validateSubForm(allValues) {
      return new Promise((resolve, reject) => {
        Promise.all([])
          .then(() => {
            resolve(allValues)
          })
          .catch((e) => {
            if (e.error === VALIDATE_FAILED) {
              // 如果有未通过表单验证的子表，就自动跳转到它所在的tab
              this.activeKey = e.index == null ? this.activeKey : this.refKeys[e.index]
            } else {
              console.error(e)
            }
          })
      })
    },
    /** 整理成formData */
    classifyIntoFormData(allValues) {
      let main = Object.assign(this.model, allValues.formValue)
      return {
        ...main, // 展开
        packagingInboundOrderDetailList: allValues.tablesValue[0].tableData,
        packagingInboundOrderMaterialList: allValues.tablesValue[1].tableData,
        packagingInboundOrderItemList: allValues.tablesValue[2].tableData,
      }
    },
    validateError(msg) {
      this.$message.error(msg)
    },
    // 新增检验
    handleAddCard() {
      this.cardList.push({
        groupId: null,
        materialItems: []
      });
    },
    // 删除卡片
    handleDeleteCard(index) {
      this.cardList.splice(index, 1);
    },
    handleDelete({ deleteRows }, index) {
    const items = this.cardList[index].materialItems;
    this.cardList[index].materialItems = items.filter(row => 
      !deleteRows.some(item => item.id === row.id))
    },
    // 变更物料
    changeMaterial(){
      this.$refs.selectGoodsList.add()
    },
    async goodRowsOk(datas) {
      if(null == datas || undefined == datas || !datas){
        return
      }
      if(this.materialColumns.materialName == datas.name && this.materialColumns.materialCode == datas.code){
        return
      }
      this.ifChangeMaterial = true;
      this.ifFenerateColumns = false;
      try {
        this.model.isReplaced = 1;
        this.materialColumns = [datas].map(item => ({
          materialName: item.name,
          materialCode: item.code,
          customerMaterialCode: item.customCode,
          specificationModel: item.noneSpec,
          unit: item.meUnit,
          materialId: item.id,
          secondaryUnit: item.auUnit,
          ...item
        }));
        // 强制销毁并重建表格组件
        await this.$nextTick();
        // 重新生成动态列
        this.generateColumns();
        // 如果已选择班组，重新加载班组数据
        if (this.model.packagingTeamId) {
          await this.handleTeamChange();
          await this.reloadPackageMaterialList(datas)
        }
      } catch (error) {
        console.error(error);
      } finally {
        this.ifFenerateColumns = true;
        this.ifChangeMaterial = false;
      }
    },
    // 更新物料信息
    reloadPackageMaterialList(materialData){
      this.packageMaterialList = [{
        ...materialData,
        workType: '1',
        materialCode: materialData.code,
        materialName: materialData.name,
        customerMaterialCode: materialData.customCode,
        specificationModel: materialData.noneSpec,
        unit: materialData.meUnit,
        materialId: materialData.id,
        secondaryUnit: materialData.auUnit,
        unitConversionRate: materialData.coRate,
      }];
      this.packageMaterialSmallList = [{
        ...materialData,
        workType: '2',
        materialCode: materialData.code,
        materialName: materialData.name,
        customerMaterialCode: materialData.customCode,
        specificationModel: materialData.noneSpec,
        unit: materialData.meUnit,
        materialId: materialData.id,
        secondaryUnit: materialData.auUnit,
        unitConversionRate: materialData.coRate,
      }];
    },
  },
}
</script>

<style scoped>
/* 固定合计行样式 */
/* .custom-summary-table >>> .vxe-table--body-wrapper table tbody tr:last-child td {
  position: sticky;
  bottom: 0;
  box-shadow: 0 -2px 6px rgba(0,0,0,0.1);
} */
</style>
